<!-- LiveList.vue -->
<template>
    <div class="live-list">
        <!-- 顶部操作栏 -->
        <div class="top-bar">
            <div>
                <div>审核状态</div>
                <el-select v-model="query.statusSelect" placeholder="全部" style="width:200px;margin-top:12px"
                    @change="handleQuery">
                    <el-option label="全部" value="" />
                    <el-option label="审核通过" value="pass" />
                    <el-option label="待审核" value="pending" />
                    <el-option label="已驳回" value="reject" />
                    <el-option label="待提交" value="unsubmit" />
                </el-select>
            </div>

            <div>
                <el-input v-model="query.title" placeholder="请输入直播间标题" style="width:240px;margin-top:12px"
                    @keyup.enter="handleQuery" />
                <el-button type="primary" @click="handleQuery" style="margin-top:12px;margin-left: 10px;">
                    查询
                </el-button>
            </div>
        </div>

        <div class="top-bar">
            <el-tabs v-model="status" @change="handleQuery">
                <el-tab-pane label="全部" name="0" />
                <el-tab-pane label="待开播" name="1" />
                <el-tab-pane label="直播中" name="2" />
                <el-tab-pane label="已结束" name="3" />
            </el-tabs>

            <el-button type="primary" @click="createVisible = true">
                + 创建直播计划
            </el-button>
        </div>

        <!-- 列表 -->
        <el-table :data="tableData" stripe v-loading="loading">
            <el-table-column prop="title" label="直播标题" width="320" />
            <el-table-column prop="startTime" label="开播时间" width="160" />
            <el-table-column prop="type" label="直播类型" width="130" />
            <el-table-column prop="status" label="直播状态" width="130">
                <template #default="{ row }">
                    <el-tag :type="row.status === 'living' ? 'success' : ''"
                        :effect="row.status === 'end' ? 'light' : 'plain'" :class="{
                            'status-ready': row.status === 'ready',
                            'status-living': row.status === 'living',
                            'status-end': row.status === 'end'
                        }">
                        {{ row.statusText }}
                    </el-tag>
                </template>
            </el-table-column>

            <el-table-column prop="reserve" label="预约人数" width="110" />
            <el-table-column prop="audit" label="审核状态" width="130">
                <template #default="{ row }">
                    <el-tag :class="`audit-status-${row.audit}`">
                        {{ row.auditText }}
                    </el-tag>
                </template>
            </el-table-column>

            <el-table-column label="链接" width="120">
                <template #default="scope">
                    <el-button :class="scope.row.reviewStatus = 1 ? 'btn-link-blue' : 'btn-link-gray'"
                        @click="scope.row.reviewStatus = 1 && showLinkDialog(scope.row)"
                        size="small">
                        生成链接
                    </el-button>
                </template>
            </el-table-column>

            <el-table-column label="操作" width="140" fixed="right">
                <template #default="{ row }">
                    <el-button link type="primary" @click="handleView(row)">查看</el-button>
                    <el-button v-if="row.audit === 'reject'" link type="primary" @click="editRow(row)">
                        修改
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
            <el-pagination v-model:current-page="page.current" v-model:page-size="page.size" :total="page.total"
                layout="prev, pager, next, jumper, ->, total" @current-change="handleQuery" style="margin-top:16px;" />
        </div>

        <!-- 弹窗 -->
        <el-dialog v-model="linkDialogVisible" title="生成链接" width="500px">
            <div class="link-dialog-content">
                <div class="form-item">
                    <label>直播标题：</label>
                    <el-input v-model="currentLinkData.title" readonly />
                </div>
                <div class="form-item">
                    <label>直播时间：</label>
                    <el-input v-model="currentLinkData.startTime" readonly />
                </div>
                <div class="form-item">
                    <label>链接地址: </label>
                    <div class="link-input">
                        <el-input v-model="currentLinkData.link"  />
                    </div>
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="linkDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleCopyAndShare">复制分享</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 创建直播 -->
        <liveorplaybackDetail v-model="createVisible" :row-data="currentRow" @success="handleCreated" />
        <!-- 查看/修改 -->
        <livepreviewDetail v-model="detailVisible" :row-data="currentRow" @refresh="fetchData"
            @delete="handleDeleteLive" />
    </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import liveorplaybackDetail from './liveorplaybackDetail.vue'
import livepreviewDetail from './livepreviewDetail.vue'
import { getInfo } from '@/api/plan'

/* ===== 状态映射 ===== */
const STATUS_MAP = {
    0: [],            // 全部
    1: [1],           // 待开播
    2: [2],           // 直播中
    3: [3]            // 已结束
}
const AUDIT_STATUS_MAP = {
    0: 'unsubmit',
    1: 'pending',
    2: 'pass',
    3: 'reject'
}
const AUDIT_STATUS_TEXT = {
    0: '待审核',
    1: '审核通过',
    2: '已驳回',
    
}
const LIVE_STATUS_MAP = {
    1: 'ready',
    2: 'living',
    3: 'end'
}
const LIVE_STATUS_TEXT = {
    1: '待开播',
    2: '直播中',
    3: '已结束'
}

/* ===== 响应式数据 ===== */
const loading = ref(false)
const detailVisible = ref(false)
const currentRow = ref({})
const createVisible = ref(false)

/* ===== 弹窗相关 ===== */
const linkDialogVisible = ref(false)
const currentLinkData = reactive({
    title: '',
    startTime: '',
    link: ''
})
const showLinkDialog = (row) => {
    currentLinkData.title = row.title
    currentLinkData.startTime = new Date(row.startTime).toLocaleString()
   
    currentLinkData.link = row.link
    linkDialogVisible.value = true
}
const handleCopyAndShare = () => {
    navigator.clipboard.writeText(currentLinkData.link).then(() => {
        ElMessage.success('复制成功')
        linkDialogVisible.value = false
    })
}

/* ===== 查询条件 ===== */
const query = reactive({
    title: '',
    statusSelect: ''
})
const status = ref('0')

/* ===== 分页 ===== */
const page = reactive({
    current: 1,
    size: 10,
    total: 0
})

/* ===== 表格数据 ===== */
const tableData = ref([])

/* 将后端结构转成前端需要的数据结构 */
const formatLiveData = (records) =>
    records.map((item) => ({
        id: item.id,
        title: item.livestreamTitle,
        startTime: item.livestreamStartTime,
        type: item.liveType === 1 ? '人工直播' : item.liveType === 2 ? '文件直播' : '人工直播',
        status: LIVE_STATUS_MAP[item.liveStatus] || LIVE_STATUS_MAP[item.livestreamStatus] || 'end',
        statusText: LIVE_STATUS_TEXT[item.liveStatus] || LIVE_STATUS_TEXT[item.livestreamStatus] || '已结束',
        reserve: item.livestreamReservationNum || 0,
        audit: AUDIT_STATUS_MAP[item.reviewStatus] || 'unsubmit',
        auditText: AUDIT_STATUS_TEXT[item.reviewStatus],
        link: item.livePlayUrl || item.livePushUrl || '', // 使用播放URL作为链接
        rawData: item
    }))

/* ===== 拉取数据 ===== */
async function fetchData() {
    loading.value = true
    try {
        const params = {
            userId: Number(localStorage.getItem('userId')),
            token: localStorage.getItem('token'),
            pageNum: page.current,
            pageSize: page.size,
            liveStatus: STATUS_MAP[status.value]?.[0] ?? undefined,
            reviewStatus:
                query.statusSelect !== '' ? Object.keys(AUDIT_STATUS_MAP).find(k => AUDIT_STATUS_MAP[k] === query.statusSelect) : undefined,
            livestreamTitle: query.title || undefined
        }
        const { code, data } = await getInfo(params)
        if (code === 200 ) {
            tableData.value = formatLiveData(data.records || [])
            console.log(tableData);
            
            page.total = data.totalCount || 0
        } else {
            tableData.value = []
            page.total = 0
        }
    } catch (e) {
        ElMessage.error('获取直播列表失败，请稍后重试')
    } finally {
        loading.value = false
    }
}

/* ===== 查询按钮 ===== */
function handleQuery() {
    page.current = 1
    fetchData()
}

/* ===== 监听条件变化 ===== */
watch([status, () => query.statusSelect, () => query.title], handleQuery)

/* ===== 创建成功的回调 ===== */
function handleCreated(newLiveData) {
    tableData.value.unshift(newLiveData)
    page.total += 1
    ElMessage.success('创建成功，已加入待审核列表')
    createVisible.value = false
}

/* ===== 查看/修改 ===== */
const handleView = (row) => {
    currentRow.value = row
    if (row.audit === 'unsubmit') {
        createVisible.value = true
    } else {
        detailVisible.value = true
    }
}
const editRow = (row) => {
    currentRow.value = { ...row, isEdit: true }
    detailVisible.value = true
}

/* ===== 删除 ===== */
const handleDeleteLive = (row) => {
    ElMessageBox.confirm('确定要删除该直播吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(() => {
            // 此处应调用删除接口，再刷新列表
            fetchData()
            ElMessage.success('删除成功')
        })
        .catch(() => { })
}

/* ===== 初始化 ===== */
fetchData()
</script>

<style scoped>
.top-bar {
    margin-bottom: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: white;
    padding: 10px;
    border-radius: 10px;
}

.pagination-container {
    display: flex;
    align-items: center;
    justify-content: flex-end;
}

::v-deep(.el-tabs__nav-wrap::after) {
    display: none;
}

.status-ready {
    color: #fa8c16;
    border-color: #fa8c16;
    background-color: rgba(250, 140, 22, 0.1);
}

.status-living {
    color: #2d7af7;
    border-color: #2d7af7;
    background-color: rgba(45, 122, 247, 0.1);
}

.status-end {
    color: #333;
    border: 1px solid #d9d9d9;
    background-color: #fafafa;
}

.audit-status-pending {
    color: #fa8c16;
    border-color: #fa8c16;
    background-color: rgba(250, 140, 22, 0.1);
}

.audit-status-pass {
    color: #2d7af7;
    border-color: #2d7af7;
    background-color: rgba(45, 122, 247, 0.1);
}

.audit-status-reject {
    color: #f5222d;
    border-color: #f5222d;
    background-color: rgba(245, 34, 45, 0.1);
}

.audit-status-unsubmit {
    color: #666;
    border-color: #d9d9d9;
    background-color: rgba(217, 217, 217, 0.1);
}

.btn-link-blue {
    color: #fff;
    background-color: #409eff;
    border-color: #409eff;
}

.btn-link-blue:hover {
    background-color: #66b1ff;
    border-color: #66b1ff;
}

.btn-link-gray {
    color: #909399;
    background-color: #f4f4f5;
    border-color: #f4f4f5;
}

.btn-link-gray:hover {
    background-color: #e9e9eb;
    border-color: #e9e9eb;
}

.form-item {
    margin-bottom: 20px;
    display: flex;
    flex-direction: column;
}

.form-item label {
    width: 80px;
    margin: 8px;
    font-size: 14px;
    color: #606266;
}

.link-input {
    width: 100%;
    display: flex;
}

.link-input .el-input {
    flex: 1;
    margin-right: 10px;
}

.dialog-footer {
    text-align: center;
}
</style>